<?php

namespace plugin\laoha\app\model;

use plugin\admin\app\model\User;
use plugin\laoha\app\model\AttachUrl;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/**
 * @property integer $id 主键(主键)
 * @property string $name 名称
 * @property string $url url
 * @property string $thumb url
 * @property integer $user_id 会员 
 * @property integer $file_size 文件大小
 * @property string $mime_type mime类型
 * @property integer $image_width 图片宽度
 * @property integer $image_height 图片高度
 * @property string $ext 扩展名
 * @property string $storage 存储位置
 * @property string $type 类别
 * @property string $created_at 上传时间
 * @property string $updated_at 更新时间
 */
class Attach extends Base
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'ha_attaches';

  
    
    protected static function booted()
    { 

        static::deleted(function ($model) {            
            AttachUrl::where('url',$model->url)->delete();
            if($model->storage=='local' && strpos($model->url,'/')===0){

                $paths = str2arr($model->url,"/");
                if($paths[1]=='app' && count($paths)>3){
                    $paths[1] = 'plugin';
                    $paths[2] = $paths[2].'/public';
                    $path = base_path().arr2str($paths,'/');
                }else{
                    $path = public_path().$model->url;
                }
                unlink($path);  //物理删除
            }            
        });                
    }   


    public function urls(): HasMany
    {
        return $this->hasMany(AttachUrl::class,'url','url');
    }    

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class,'user_id','id');
    }  

    public function data_format($data,$type='list')
    {
        if($type=='list' && !empty($data['file_size'])){            
            $data['file_size'] = getSize($data['file_size']);
        }
        return $data;
    }      
}
